package com.leehongrim.tools.image;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ImageStitcher {

    // 拼接方向：横向、纵向
    public enum Direction { HORIZONTAL, VERTICAL }

    /**
     * 拼接图片
     * @param imagePaths 待拼接图片路径列表
     * @param direction 拼接方向（横向/纵向）
     * @param gap 图片间距（像素）
     * @param bgColor 背景色（如 Color.WHITE）
     * @param outputPath 输出图片路径（含格式，如 "result.png"）
     * @throws IOException 图片读写异常
     */
    public static void stitchImages(List<File> imagePaths, Direction direction, int gap, Color bgColor, String outputPath) throws IOException {
        // 加载所有图片
        List<BufferedImage> images = new ArrayList<>();
        for (File path : imagePaths) {
            BufferedImage img = ImageIO.read(path);
            if (img == null) {
                throw new IOException("无法加载图片：" + path);
            }
            images.add(img);
        }

        // 计算拼接后图片的宽高
        int totalWidth = 0;
        int totalHeight = 0;
        int maxWidth = 0;
        int maxHeight = 0;

        for (BufferedImage img : images) {
            maxWidth = Math.max(maxWidth, img.getWidth());
            maxHeight = Math.max(maxHeight, img.getHeight());
            if (direction == Direction.HORIZONTAL) {
                totalWidth += img.getWidth();
            } else {
                totalHeight += img.getHeight();
            }
        }

        // 加上间距（n张图片有n-1个间距）
        int gapTotal = gap * (images.size() - 1);
        if (direction == Direction.HORIZONTAL) {
            totalWidth += gapTotal;
            totalHeight = maxHeight;
        } else {
            totalHeight += gapTotal;
            totalWidth = maxWidth;
        }

        // 创建拼接画布
        BufferedImage result = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = result.createGraphics();
        g.setColor(bgColor);
        g.fillRect(0, 0, totalWidth, totalHeight); // 填充背景

        // 绘制每张图片到画布
        int currentX = 0;
        int currentY = 0;
        for (BufferedImage img : images) {
            // 绘制图片（横向拼接：X轴累加；纵向拼接：Y轴累加）
            g.drawImage(img, currentX, currentY, null);

            // 更新下一张图片的起始位置
            if (direction == Direction.HORIZONTAL) {
                currentX += img.getWidth() + gap;
            } else {
                currentY += img.getHeight() + gap;
            }
        }

        // 释放资源
        g.dispose();

        // 保存结果图片
        String format = outputPath.substring(outputPath.lastIndexOf(".") + 1);
        ImageIO.write(result, format, new File(outputPath));
    }

}